from typing import Any

from aiogram import F, types
from aiogram_dialog import Dialog, DialogManager, Window
from aiogram_dialog.widgets.input import TextInput
from aiogram_dialog.widgets.kbd import Back, Button, Cancel, Start
from aiogram_dialog.widgets.text import Const, Format
from sqlalchemy.ext.asyncio import AsyncSession

from app.bot.states.user import LinksState
from app.bot.utils.logger import logger
from app.database.requests import add_links, get_links


async def get_user_links(
    session: AsyncSession, dialog_manager: DialogManager, **kwargs
):
    user_id: int = dialog_manager.event.from_user.id
    links = await get_links(session, user_id)

    return {
        "links": links,
    }


async def update_links(
    message: types.Message, widget: Any, manager: DialogManager, links: str
):
    session = manager.middleware_data.get("session")
    user_id = message.from_user.id
    
    try:
        await add_links(session, user_id, links)
        await message.answer("Ссылки обновлены")
        await manager.done()
    except Exception as e:
        logger.exception(e)
        await message.answer("Ошибка при обновлении ссылок")


links_dialog = Dialog(
    Window(
        Const("Список товаров\n"),
        Format("{links}", when=F["links"]),
        Start(
            Const("Обновить товары"),
            id="add_links",
            state=LinksState.new_links,
        ),
        state=LinksState.links_list,
        getter=get_user_links,
    ),
    Window(
        Const("Введите ссылки на товары каждую с новой строки"),
        TextInput("linkslist", str, on_success=update_links),
        Back(Const("⬅️ Назад")),
        state=LinksState.new_links,
    ),
)
